package com.tzy.for10evalue.common.threadpool;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;


/**
 * 开启spring异步；配置业务线程池
 */
@Configuration
@EnableAsync
public class AsyncConfig {

    /**
     * 创建SAP同步业绩数据线程池
     *
     * @return
     */
    @Bean("sapSyncPerformanceThreadPool")
    public Executor sapSyncPerformanceThreadPool() {
        /**
         * 同步SAP信息任务线程池
         * 单线程，防止出现任务并行
         */
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(1);
        executor.setMaxPoolSize(1);
        executor.setQueueCapacity(300);
        executor.setThreadNamePrefix("syncSapPerformance-");
        executor.initialize();
        return executor;
    }

    /**
     * 创建SAP同步客户组数据线程池
     *
     * @return
     */
    @Bean("sapSyncCustomerGroupExecutor")
    public Executor sapSyncCustomerGroupExecutor() {
        /**
         * 同步SAP信息任务线程池
         * 单线程，防止出现任务并行
         */
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(1);
        executor.setMaxPoolSize(1);
        executor.setQueueCapacity(1);
        executor.setThreadNamePrefix("syncSapCustomerGroup-");
        executor.initialize();
        return executor;
    }

    /**
     * 导出记录线程池
     * @return
     */
    @Bean("exportExecutor")
    public Executor exportExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(200);
        executor.setThreadNamePrefix("exportRecord-");
        executor.initialize();
        return executor;
    }

    /**
     * 业绩同步线程池
     * @return
     */
    @Bean("syncSapSalePerformanceThreadPool")
    public Executor syncSapSalePerformanceThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(40);
        executor.setQueueCapacity(2000);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("syncSapSalePerformanceThreadPool-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        return executor;
    }
}
